package com.bai.Utils;

import com.bai.Mapper.AdminMapper;
import com.bai.Pojo.Admin;
import com.bai.Pojo.SysPermission;
import com.bai.Pojo.SysRole;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


/**
 * @todo 自定义 Realm,查询数据库并返回正确的数据
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private AdminMapper adminMapper;
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户输入的账户
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        System.out.println(token.getPrincipal());
        // 通过username从数据库中查找 UserInfo 对象
        // 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        Admin userInfo = adminMapper.findAdminByUsername(username);
        //4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
        if(userInfo==null){
            throw  new UnknownAccountException("账户不存在！");
        }
        //验证密码
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userInfo, // 用户名
                userInfo.getPassword(), // 密码
                ByteSource.Util.bytes(userInfo.getSalt()), // salt=username+salt
                getName() // realm name
        );
        System.out.println(simpleAuthenticationInfo);
        return simpleAuthenticationInfo;
    }



    //授权管理
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 能进入这里说明用户已经通过验证了
        Admin userInfo = (Admin) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<SysRole> roles = adminMapper.findRoles(userInfo.getUsername());
        if (roles!=null){
            for (SysRole role : roles) {
                simpleAuthorizationInfo.addRole(role.getName());
                List<SysPermission> permissions = adminMapper.findPermissions(role.getName());
                if (permissions!=null){
                    for (SysPermission permission : permissions) {
                        simpleAuthorizationInfo.addStringPermission(permission.getName());
                    }
                }

            }
        }
        return simpleAuthorizationInfo;
    }
}
